<?php include("header_login_required.php"); ?>
<?php
  	$today = date('d/m/Y');

    $dep = $_POST['department'];
  	$round = $_POST['round'];
  	$homeTeam = $_SESSION['homeTeam'];
  	$visitTeam = $_SESSION['visitTeam'];
  	$user = $_SESSION['user'];
  	$comment = $_POST['comment'];

  	$homePlayerRank = array();
  	$homePlayerRank[1] = $_POST['homePlayerRank_1'];
  	$homePlayerRank[2] = $_POST['homePlayerRank_2'];
  	$homePlayerRank[3] = $_POST['homePlayerRank_3'];
  	$homePlayerRank[4] = $_POST['homePlayerRank_4'];
  	$homePlayerRank[5] = $_POST['homePlayerRank_5'];
  	$homePlayerRank[6] = $_POST['homePlayerRank_6'];

  	$visitPlayerRank = array();
  	$visitPlayerRank[1] = $_POST['visitPlayerRank_1'];
  	$visitPlayerRank[2] = $_POST['visitPlayerRank_2'];
  	$visitPlayerRank[3] = $_POST['visitPlayerRank_3'];
  	$visitPlayerRank[4] = $_POST['visitPlayerRank_4'];
  	$visitPlayerRank[5] = $_POST['visitPlayerRank_5'];
  	$visitPlayerRank[6] = $_POST['visitPlayerRank_6'];

  	$matchResult = array();
  	$matchResult[1] = $_POST['result_1'];
  	$matchResult[2] = $_POST['result_2'];
  	$matchResult[3] = $_POST['result_3'];
  	$matchResult[4] = $_POST['result_4'];
  	$matchResult[5] = $_POST['result_5'];
  	$matchResult[6] = $_POST['result_6'];
    
    

  	if ( empty($dep) ) {
    	rejectIfError(null, "U moet een afdeling opgeven.");
  	} else if ( empty($round) ) {
    	rejectIfError(null, "U moet een rondenummer opgeven.");
  	} else if ( empty($homeTeam) ) {
    	rejectIfError(null, "U moet een thuisploeg opgeven.");
  	} else if ( empty($visitTeam) ) {
    	rejectIfError(null, "U moet een bezoekersploeg opgeven.");
  	} else if ( empty($dep) ) {
    	rejectIfError(null, "U moet een afdeling opgeven.");
  	}
    
    // change player key's to 0 (forfait) in case they try to cheat the system
    
    $index = 0;
    foreach ($matchResult as $item) { 
        
        $index++;
        
        if ( $item == '1 - FF' ) {
            $visitPlayerRank[$index] = 0;        
        } else if ( $item == 'FF - 1' ) {
            $homePlayerRank[$index] = 0;
        }
            
    }   
    

  	$connect = mysql_connect(DB_SERVER, DB_USER, DB_PWD);
	mysql_select_db(DB_CATALOG);

	mysql_query("SET AUTOCOMMIT=0", $connect);
  	mysql_query("BEGIN", $connect);

  	$query = sprintf("select c.calendar_id from zt_calendar_pairing cp join
	    zt_calendar c on c.calendar_id = cp.calendar_id 
	    join zt_tournament zt on zt.tournament_id = c.tournament_id 
	    where c.round_nr = %u and zt.iscurrent = 1
	    and cp.home_team = %u and cp.visit_team = %u", 
  		$round, $homeTeam, $visitTeam);
  	$result = mysql_query($query, $connect);
  	rejectTranIfError($query, "insert_result.php: selecteren rondegegevens is mislukt.");
  	$row = mysql_fetch_assoc($result);
  	$calendar_id = $row['calendar_id'];

  	$query = sprintf("select group_id from zt_group g
  		join zt_tournament t on t.tournament_id = g.tournament_id
  		where t.iscurrent = 1 and group_name = '%s'", $dep);
    
	$result = mysql_query($query, $connect);
  	$row = mysql_fetch_assoc($result);
  	$groupId = $row['group_id'];

  	// fetch the current player lists
  	
  	$query = "select pl.player_list_id from zt_player_list pl
  		join club c on c.club_id = pl.club_id
  		join zt_team te on te.club_id = c.club_id
  		where pl.inactive = 0
  		and pl.date_approved is not null
  		and te.team_id = ".$homeTeam." order by pl.player_list_id desc";
	$result = mysql_query($query, $connect);
  	$row = mysql_fetch_assoc($result);
  	$homePlayerListId = $row['player_list_id'];
  	
  	$query = "select pl.player_list_id from zt_player_list pl
  		join club c on c.club_id = pl.club_id
  		join zt_team te on te.club_id = c.club_id
  		where pl.inactive = 0
  		and pl.date_approved is not null 
  		and te.team_id = ".$visitTeam." order by pl.player_list_id desc";
	$result = mysql_query($query, $connect);
  	$row = mysql_fetch_assoc($result);
  	$visitPlayerListId = $row['player_list_id'];
  	
  	// insert the game
  	
  	$query = sprintf("insert into zt_game (calendar_id, home_team, visit_team,
    	game_date, comment, author, group_id, home_player_list_id, 
    	visit_player_list_id) values (%u, %u, %u, '%s', '%s', %u, %u, %u, %u)", 
  		$calendar_id, $homeTeam, $visitTeam, date('d/m/Y'), $comment, 
  		$user->user_id, $groupId, $homePlayerListId, $visitPlayerListId);
  	mysql_query($query, $connect);
  	rejectTranIfError($query, "insert_result.php: invoeren algemene gegevens ronde is mislukt.");

  	$query = "SELECT LAST_INSERT_ID() AS game_id";
	$result = mysql_query($query, $connect);
	$row = mysql_fetch_assoc($result);
	$game_id = $row['game_id'];

	if ($game_id == 0) {
	  	rejectTranIfError($query, "insert_result.php: nummer partij niet gevonden.");
	}

    $homeForfait = 0;
    $visitForfait = 0;
    
  	for ($i = 1; $i <= 6; $i++) {
    	if ( (!empty($homePlayerRank[$i]) || !empty($visitPlayerRank[$i]))
      		&& !empty($matchResult[$i]) ) {

      		$query = sprintf("select result_type_id from zt_result_type where result = '%s'", $matchResult[$i]);
      		$result = mysql_query($query, $connect);
      		rejectTranIfError($query, "insert_result.php: selecteren resultaat type is mislukt.");
  			$row = mysql_fetch_assoc($result);
  			$result_type_id = $row['result_type_id'];
            
            if ( $homeForfait == 0 && $homePlayerRank[$i] == 0 ) {
                $homeForfait = $i;    
            }
            
            if ( $visitForfait == 0 && $visitPlayerRank[$i] == 0 ) {
                $visitForfait = $i;    
            }
            
  			$homeError = getBoardError($i, $homePlayerRank, $homeTeam, $homeForfait);
  			$visitError = getBoardError($i, $visitPlayerRank, $visitTeam, $visitForfait);
  			
      		$query = sprintf("insert into zt_game_player (game_id, board_nr,
        		index_nr_home, index_nr_visit, result_type_id, home_error_id,
        		visit_error_id) values (%u, %u, %u, %u, %u, %u, %u)", 
      			$game_id, $i, $homePlayerRank[$i], $visitPlayerRank[$i], 
      			$result_type_id, $homeError, $visitError);

      		mysql_query($query, $connect);
      		rejectTranIfError($query, "insert_result.php: selecteren rondegegevens is mislukt.");
    	}
  	}

	function getBoardError($boardNr, $playerRanks, $teamPlayed, $forfait) {
	  	
		$connect = mysql_connect(DB_SERVER, DB_USER, DB_PWD);
		mysql_select_db(DB_CATALOG);
        
        if ($forfait > 0 && $boardNr > $forfait) {
            $query = "select error_id from zt_game_player_error where error_code = 'inherited_forfait'";
            $result = mysql_query($query);
            $row = mysql_fetch_assoc($result);
            return $row['error_id'];
        }
		
		$result = mysql_query("select pl.player_list_id 
	    	from zt_player_list pl
	        join club c on c.club_id = pl.club_id 
	        join zt_team t on t.club_id = c.club_id
	        join zt_tournament tr on tr.tournament_id = pl.tournament_id
	        where tr.iscurrent = 1 and pl.date_approved is not null 
	        and t.team_id = ".$teamPlayed);
    	$record = mysql_fetch_assoc($result);
    	$pl = $record['player_list_id'];
		
    	if (empty($playerRanks[$boardNr])) {
    		return null;
    	}
    	
    	$query = "select zp.team_id from zt_player_list zpl
    		join zt_player zp on zp.player_list_id = zpl.player_list_id
	    	where zp.index_nr = ".$playerRanks[$boardNr]."
	    	and zpl.player_list_id = ".$pl." order by zp.index_nr";
  		$result = mysql_query($query, $connect);
  		rejectTranIfError($query, "insert_result.php: opvragen team thuisspeler op bord ".$boardNr." is mislukt.");
  		$row = mysql_fetch_assoc($result);
  		$playerListTeam = $row['team_id'];
  			
      	if (!empty($homePlayerListTeam)) {
	  	    // effective player
	  	    $query = "select team_nr, group_id from zt_team where team_id = ".$playerListTeam;
	  	    $result = mysql_query($query, $connect);
	  	    $row = mysql_fetch_assoc($result);
	  	    $playerListTeam = $row['team_nr'];
	  	    $playerListDepartment = $row['group_id'];
	  	    	
	  	    $query = "select team_nr, group_id from zt_team where team_id = ".$teamPlayed;
	  	    $result = mysql_query($query, $connect);
	  	    $row = mysql_fetch_assoc($result);
	  	    $actualTeamPlayed = $row['team_nr'];
	  	    $actualDepartment = $row['group_id'];
	  	    	
	  	    if ($actualTeamPlayed > $playerListTeam) {
	  	    	// cannot play in lower team
	  	    	$query = "select error_id from zt_game_player_error where error_code = 'team_to_low'";
	  	    	$result = mysql_query($query);
	  	    	$row = mysql_fetch_assoc($result);
	  	    	return $row['error_id'];
	  	    } else if ($playerListTeam != $actualTeamPlayed) {
	  	    	// played in higher team
	  	    	if ($actualDepartment == $playerListDepartment) {
	  	    		// but in same department, is not allowed
	  	    		$query = "select error_id from zt_game_player_error where error_code = 'wrong_team'";
		  	    	$result = mysql_query($query);
	  	    		$row = mysql_fetch_assoc($result);
		  	    	return $row['error_id'];
	  	    	}
	  	    }
		}
	  	    
      	$previousBoard = $boardNr-1;
	  	if (isset($playerRanks[$previousBoard])) {
	  		$previousRank = $playerRanks[$previousBoard];
	  	    $playerRank = $playerRanks[$boardNr];
	  	    if ($previousRank > $playerRank) {
	  	    	// player at wrong board
	  	    	$query = "select error_id from zt_game_player_error where error_code = 'invalid_order'";
	  	    	$result = mysql_query($query);
	  	    	$row = mysql_fetch_assoc($result);
	  	    	return $row['error_id'];
	  	    }
		}
		
		return null;
	}
  	
  	mysql_query("COMMIT", $connect);
 	redirect("/tornooien/zt-php/calculate_stats.php?dep=".$dep);
?>

<?php include("footer.php"); ?>
